import {
  queryAllTheme,
  queryAllActivity,
  queryAllWay
} from '@/api/theme-travel'

const getDefaultState = () => {
  return {
    theme: [],
    way: [],
    activity: []
  }
}

const state = { ...getDefaultState() }

const mutations = {
  INIT: (state) => {
    state = { ...getDefaultState() }
  },
  SET_THEME: (state, theme) => {
    state.theme = theme
  },
  SET_ACTIVITY: (state, activity) => {
    state.activity = activity
  },
  SET_WAY: (state, way) => {
    state.way = way
  }
}

const actions = {
  init({ commit }) {
    commit('INIT')
  },
  setTheme({ commit }) {
    return new Promise((resolve, reject) => {
      if (state.theme.length) {
        resolve(state.theme)
      }
      queryAllTheme().then(res => {
        commit('SET_THEME', res.data)
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  setActivity({ commit }) {
    return new Promise((resolve, reject) => {
      queryAllActivity().then(res => {
        commit('SET_ACTIVITY', res.data)
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  setWay({ commit }) {
    return new Promise((resolve, reject) => {
      queryAllWay().then(res => {
        commit('SET_WAY', res.data)
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

